package net.guerlab.smart.wx.service.service.impl;

import net.guerlab.smart.platform.commons.util.OrderEntityUtils;
import net.guerlab.smart.platform.server.service.BaseServiceImpl;
import net.guerlab.smart.wx.core.exception.UserTagNameInvalidException;
import net.guerlab.smart.wx.core.exception.UserTagNameRepeatException;
import net.guerlab.smart.wx.service.entity.UserTag;
import net.guerlab.smart.wx.service.mapper.UserTagMapper;
import net.guerlab.smart.wx.service.service.UserTagService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 用户标签服务实现
 *
 * @author guer
 */
@Service
public class UserTagServiceImpl extends BaseServiceImpl<UserTag, Long, UserTagMapper> implements UserTagService {

    @Override
    protected void insertBefore(UserTag entity) {
        String tagName = StringUtils.trimToNull(entity.getTagName());

        if (tagName == null) {
            throw new UserTagNameInvalidException();
        }

        if (selectByName(tagName) != null) {
            throw new UserTagNameRepeatException();
        }

        entity.setTagId(sequence.nextId());
        entity.setTagName(tagName);
        OrderEntityUtils.propertiesCheck(entity);
    }

    @Override
    protected void updateBefore(UserTag entity) {
        String tagName = StringUtils.trimToNull(entity.getTagName());

        if (tagName != null) {
            UserTag other = selectByName(tagName);
            if (other != null && !Objects.equals(other.getTagId(), entity.getTagId())) {
                throw new UserTagNameRepeatException();
            }
        }
        entity.setTagName(tagName);
    }
}
